#include <iostream>
#include <set>

using namespace std;

const int INF = 1e7;

int n;
set<int> mp;

int main()
{
    cin >> n;
    mp.insert(-INF);
    mp.insert(INF);
    int ret;
    cin >> ret;
    mp.insert(ret);
    for(int i = 2;i <= n;i++)
    {
        int x; cin >> x;
        auto t = mp.lower_bound(x);
        auto tmp = t;
        tmp--;
        ret += min(abs(*tmp - x),abs(*t - x));
        mp.insert(x);
    }
    cout << ret << endl;
    return 0;
}